package cn.kmsoft.common.utils;

import cn.kmsoft.common.exception.BizRuntimeException;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class FileUtil {
    private static final int BUFFER_SIZE = 2 * 1024;

    public static Boolean checkPathExist(String path){
        File file= new File(path);
        return file.exists();
    }

    public static String createTmpDir(String rootPath) {
        return createTmpDir(rootPath, "" + new Date().getTime());
    }

    public static String createTmpDir(String rootPath, String currPath) {
        File rootDir = new File(rootPath);
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }
        String outPath = rootPath + File.separator + currPath;
        File dirFile = new File(outPath);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        return outPath;
    }

    public static String createTmpRandomDir(String tempPath) {
        return createTmpRandomDir(tempPath, UUID.randomUUID().toString());
    }

    public static String createTmpRandomDir(String tempPath, String pathName) {
        String outPath = tempPath + pathName + "/";
        File dirFile = new File(outPath);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        return outPath;
    }

    public static void creatFileDir(String path) {
        File dir = new File(path);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new BizRuntimeException("创建文件夹失败");
            }
        }
    }


    /**
     * 获取文件内容
     *
     * @param f
     * @return
     */
    public static String readFile(File f) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStreamReader isr = new InputStreamReader(new FileInputStream(f), "utf-8");
        BufferedReader br = new BufferedReader(isr);
        String str;
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }

        return sb.toString();
    }

    public static String readFile(File f, String charsetStr) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStreamReader isr = new InputStreamReader(new FileInputStream(f), charsetStr);
        BufferedReader br = new BufferedReader(isr);
        String str;
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }

        return sb.toString();
    }

    /**
     * 按行从上之下顺序读取txt文件，将字符串保存到list中
     * @param f
     * @param charsetStr
     * @return
     * @throws IOException
     */
    public static List<String> readFileByLine(File f, String charsetStr) throws IOException {
        List<String> list = new ArrayList<String>();
        InputStreamReader isr = new InputStreamReader(new FileInputStream(f), charsetStr);
        BufferedReader br = new BufferedReader(isr);
        String str;
        while ((str = br.readLine()) != null) {
            list.add(str);
        }
        br.close();
        isr.close();
        return list;
    }

    /**
     * 将字符串写入文件
     *
     * @param content
     * @param path
     * @throws IOException
     */
    public static void writeFile(String content, String path) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path)), "utf-8"));
        bw.write(content);
        bw.close();
    }

    /**
     * 将字符串写入文件
     *
     * @param content
     * @param path
     * @throws IOException
     */
    public static void writeFile(String content, String path, String charsetStr) throws IOException {
        if (StringUtil.isNullOrEmpty(charsetStr)) {
            charsetStr = "utf-8";
        }
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path)), charsetStr));
        bw.write(content);
        bw.close();
    }

    /**
     *  将list<string>按行从上到下顺序地写入文件
     *
     * @param lines
     * @param path
     * @param charsetStr
     * @throws IOException
     */
    public static void writeFileByLine(List<String> lines, String path, String charsetStr) throws IOException {
        if (StringUtil.isNullOrEmpty(charsetStr)) {
            charsetStr = "utf-8";
        }
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path)), charsetStr));
        int size = lines.size();
        for(int i=0; i<size; i++) {
            String lineStr= lines.get(i);
            bw.write(lineStr);

            //bw.write("\n");
            bw.newLine();// 写入换行符
        }
        bw.flush();
        bw.close();
    }

    /**
     * 创建文件
     *
     * @throws IOException
     */
    public static boolean creatTxtFile(String path, String name) throws IOException {
        boolean flag = false;
        String filenameTemp = path + File.separator+ name + ".txt";
        File filename = new File(path);
        if (!filename.exists()) {
            filename.createNewFile();
            flag = true;
        }
        return flag;
    }
    public static boolean writeFileWithAscii(String content,String path) throws IOException {
        // 先读取原有文件内容，然后进行写入操作
        boolean flag = false;
        String filein = content + "\r\n";
        String temp = "";

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            // 文件路径
            File file = new File(path);
            // 将文件读入输入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();

            // 保存该文件原有的内容
            for (int j = 1; (temp = br.readLine()) != null; j++) {
                buf = buf.append(temp);
                // System.getProperty("line.separator")
                // 行与行之间的分隔符 相当于“\n”
                buf = buf.append(System.getProperty("line.separator"));
            }
            buf.append(filein);

            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buf.toString().toCharArray());
            pw.flush();
            flag = true;
        } catch (IOException e1) {
            // TODO 自动生成 catch 块
            throw e1;
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return flag;
    }
    

    public static boolean deleteAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }

        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            // 文件
            if (temp.isFile()) {
                temp.delete();
            }
            // 子文件夹及文件
            if (temp.isDirectory()) {
                deleteAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                deleteFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    //删除文件夹
    public static void deleteFolder(String folderPath) {
        try {
            deleteAllFile(folderPath); //删除完里面所有内容

            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);

            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     *
     * @param filePath
     * @throws IOException
     */
    public static boolean deleteFile(String filePath) throws IOException {
        if (filePath == null) {
            return false;
        }
        File file = new File(filePath);

        if (file.exists()) {
            return file.delete();
        }

        return false;
    }

    /**
     * 获取文件后缀名称
     *
     * @param fileName 如：D:\\temp\\test.txt
     * @return 返回  txt
     */
    public static String getExtensionName(String fileName) {
        if ((fileName != null) && (fileName.length() > 0)) {
            int dot = fileName.lastIndexOf('.');
            if ((dot > -1) && (dot < (fileName.length() - 1))) {
                return fileName.substring(dot + 1);
            }
        }

        return fileName;
    }

    /**
     * 获取文件名称，包含物理路径（无后缀）
     *
     * @param fileName
     * @return 如：D:\\temp\\test.txt
     * 返回  D:\\temp\\test
     */
    public static String getFileNameWithNoExtension(String fileName) {
        if ((fileName != null) && (fileName.length() > 0)) {
            int dot = fileName.lastIndexOf('.');
            if ((dot > -1) && (dot < fileName.length())) {

                return fileName.substring(0, dot);
            }
        }
        return fileName;
    }

    /**
     * 获取文件名称，不包含物理路径和后缀
     *
     * @param fileName 如：D:\\temp\\test.txt
     * @return 返回  test
     */
    public static String getFileNameWithNoPathAndExtension(String fileName) {
        if ((fileName != null) && (fileName.length() > 0)) {
            int dot = fileName.lastIndexOf(".");

            int fxg = fileName.lastIndexOf("\\");
            if ((fxg > -1) && (fxg < dot) && (dot > -1) && (dot < fileName.length())) {
                return fileName.substring(fxg + 1, dot);
            }

            int fxg1 = fileName.lastIndexOf("/");
            if ((fxg1 > -1) && (fxg1 < dot) && (dot > -1) && (dot < fileName.length())) {
                return fileName.substring(fxg1 + 1, dot);
            }
        }
        return fileName;
    }

    /**
     * 获取文件所在的文件夹目录
     *
     * @param fileName 如：D:\\temp\\test.txt
     * @return 返回  D:\\temp\\
     */
    public static String getPathOfDiskFile(String fileName) {
        if ((fileName != null) && (fileName.length() > 0)) {
            int fxg1 = fileName.lastIndexOf('\\');
            if ((fxg1 > -1) && (fxg1 < fileName.length())) {
                return fileName.substring(0, fxg1);
            }

            int fxg2 = fileName.lastIndexOf('/');
            if ((fxg2 > -1) && (fxg2 < fileName.length())) {
                return fileName.substring(0, fxg2);
            }
        }
        return fileName;
    }

    public static void createParentPath(File file) {
        File parentFile = file.getParentFile();
        if (null != parentFile && !parentFile.exists()) {
            parentFile.mkdirs(); // 创建文件夹
            createParentPath(parentFile); // 递归创建父级目录
        }
    }

    public static void createDirectory(File dir) {
        createParentPath(dir);
        if (!dir.exists() || !dir.isDirectory()) {
            dir.mkdir();
        }
    }

    public static void createDirectory(String folderPath) {
        File dir = new File(folderPath);
        //可以创建多层目录
        if (!dir.exists() || !dir.isDirectory()) {
            dir.mkdirs();
        }
    }


    public static void toZip(String zipFile, List<String> files) throws RuntimeException {
        ZipOutputStream zos = null;
        try {
            OutputStream outZip = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(outZip);
            for (String f : files) {
                File sourceFile = new File(f);
                compress(sourceFile, zos, sourceFile.getName(), false);
            }
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 压缩成ZIP 方法1
     *
     * @param srcDir           压缩文件夹路径
     * @param zipFile              压缩文件输出流
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String srcDir, String zipFile, boolean KeepDirStructure) throws RuntimeException {
        ZipOutputStream zos = null;
        try {
            OutputStream outZip = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(outZip);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
     * 递归压缩方法
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             压缩后的名称
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure)
            throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    if (StringUtils.isBlank(name)) {
                        zos.putNextEntry(new ZipEntry(name));
                    } else {
                        zos.putNextEntry(new ZipEntry(name + "/"));
                    }

                    // 没有文件，不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                        if (StringUtils.isBlank(name)) {
                            compress(file, zos, file.getName(), KeepDirStructure);
                        } else {
                            compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                        }

                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);

                    }
                }
            }
        }
    }


}